package com.shiikong_memory.yez.Arknights;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.shiikong_memory.yez.Arknights.ArknightsData.AccountData;
import com.shiikong_memory.yez.MySQLAPI.DaoImpl.AccountDataServer;
import com.shiikong_memory.yez.MySQLAPI.DaoImpl.SklandServer;
import com.shiikong_memory.yez.MySQLAPI.JavaBean.AccountDataBean;
import com.shiikong_memory.yez.MySQLAPI.JavaBean.SklandBean;
import love.forte.simbot.component.kook.event.KookChannelMessageEvent;
import love.forte.simbot.kook.api.message.SendChannelMessageApi;
import love.forte.simbot.quantcat.common.annotations.ContentTrim;
import love.forte.simbot.quantcat.common.annotations.Listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

@Component
public class GetData {

    @Autowired
    SklandServer sklandServer;

    @Autowired
    private SklandAPI sklandAPI;

    @Autowired
    AccountDataServer accountDataServer;

    private final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd");

    @Listener
    @ContentTrim
    public CompletableFuture<?> GetData(KookChannelMessageEvent event){
        String type = null;
        if (event.getSourceEvent().getContent().matches("^获取明日方舟数据$")) type = "官服";
        else if (event.getSourceEvent().getContent().matches("^获取明日方舟数据B$")) type = "bilibili服";
        else return null;
        if (type != null){
            SklandBean sklandBean = sklandServer.getByKookId(event.getAuthor().getId().toString());
            if (sklandBean == null){
                return event.replyAsync("未登录鹰角通行证，无法查询数据，请先登录鹰角通行证");
            }
            String id = sklandBean.getArknightsToken();
            if (!sklandAPI.verifyToken(id)){
                return event.replyAsync("鹰角通行证Token不合法请重新获取");
            }
            JSONObject arknightsData;
            AccountDataBean accountDataBean = accountDataServer.getByKookId(event.getAuthor().getId().toString());
            AccountData data;
            if (accountDataBean == null){
                arknightsData = updateData(event,event.getAuthor().getId().toString(), id, true, type);
                if (arknightsData == null) return null;
                data = new AccountData(arknightsData.getJSONObject("data"));
            }else {
                try {
                    Date parse1 = DF.parse(accountDataBean.getUpdateTime());
                    Date parse2 = DF.parse(DF.format(new Date()));
                    if (parse1.compareTo(parse2) == -1){
                        arknightsData = updateData(event,event.getAuthor().getId().toString(), id, false, type);
                        if (arknightsData == null) return null;
                        data = new AccountData(arknightsData.getJSONObject("data"));
                    }else {
                        data = new AccountData(accountDataBean.getStatus(), accountDataBean.getChars(), accountDataBean.getSkins());
                    }
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            String cardJson = String.format(Json,
                    event.getAuthor().getId().toString(),
                    data.getName(),
                    data.getLevel(),
                    DF.format(data.getRegisterTs()),
                    data.getResume(),
                    data.getAgentSize(),
                    data.getSkinSize(),
                    data.getEvolvePhase2Size(),
                    data.getEquipMaxSize()
                    );
            IntensiveStrategyRandom.clearCache(event.getAuthor().getId().toString());
            return event.getContent().sendAsync(SendChannelMessageApi.create(10,event.getSourceEvent().getTargetId(), cardJson));
        }
        else return null;
    }

    @Listener
    @ContentTrim
    public CompletableFuture<?> updateData(KookChannelMessageEvent event) {
        String type = null;
        if (event.getSourceEvent().getContent().matches("^获取明日方舟数据$")) type = "官服";
        else if (event.getSourceEvent().getContent().matches("^获取明日方舟数据B$")) type = "bilibili服";
        else return null;
        if (type != null) {
            SklandBean sklandBean = sklandServer.getByKookId(event.getAuthor().getId().toString());
            if (sklandBean == null) {
                return event.replyAsync("未登录鹰角通行证，无法查询数据，请先登录鹰角通行证");
            }
            String id = sklandBean.getArknightsToken();
            if (!sklandAPI.verifyToken(id)) {
                return event.replyAsync("鹰角通行证Token不合法请重新获取");
            }
            updateData(event,event.getAuthor().getId().toString(), id, false, type);
            IntensiveStrategyRandom.clearCache(event.getAuthor().getId().toString());
            return event.replyAsync("明日方舟数据已刷新（%s）".formatted(type));
        }
        return null;
    }

    /**
    @Listener
    @ContentTrim
    public CompletableFuture<?> GetData(KookChannelMessageEvent event) {
        String[] split = event.getSourceEvent().getContent().split("获取明日方舟角色数据:");
        if (split.length == 2) {
            String id = split[1];
            String code = sklandAPI.getCode(id);
            if (code == null) {
                event.replyAsync("无法获取code，请联系管理者进行修复");
                return null;
            }
            JSONObject cred = sklandAPI.getCred(code);
            if (cred == null) {
                event.replyAsync("无法获取cred，请联系管理者进行修复");
                return null;
            }
            JSONObject jsonObject = sklandAPI.get_binding_list(cred.getString("cred"), cred.getString("token"));
            if (jsonObject == null) {
                event.replyAsync("无法获取游戏角色，请确定游戏角色已创建");
                return null;
            }
            System.out.println(jsonObject);
        }
        return null;
    }
    **/

    public JSONObject updateData(KookChannelMessageEvent event,String KookId,String id, boolean add, String tyep){
        String code = sklandAPI.getCode(id);
        if (code == null){
            event.replyAsync("无法获取code，请联系管理者进行修复");
            return null;
        }
        JSONObject cred = sklandAPI.getCred(code);
        if (cred == null){
            event.replyAsync("无法获取cred，请联系管理者进行修复");
            return null;
        }
        JSONObject jsonObject = sklandAPI.get_binding_list(cred.getString("cred"), cred.getString("token"));
        if (jsonObject == null){
            event.replyAsync("无法获取游戏角色，请确定游戏角色已创建");
            return null;
        }
        String uuid = null;
        JSONArray gameList = jsonObject.getJSONObject("data").getJSONArray("list");
        for (int j=0;j<gameList.size();j++){
            if ("arknights".equals(gameList.getJSONObject(j).getString("appCode"))){
                JSONArray bingingList = gameList.getJSONObject(j).getJSONArray("bindingList");
                for (int i=0;i<bingingList.size();i++){
                    JSONObject jsonObject1 = bingingList.getJSONObject(i);
                    if (tyep.equals(jsonObject1.getString("channelName"))){
                        uuid = jsonObject1.getString("uid");
                    }
                }
            }
        }
        if (uuid == null){
            event.replyAsync("没有查询到"+tyep+"的账号,请确认账号信息");
            return null;
        }
        JSONObject arknightsData = sklandAPI.getArknightsData(cred.getString("cred"), cred.getString("token"), uuid);
        JSONObject data = arknightsData.getJSONObject("data");
        if (add){
            accountDataServer.addAccountData(KookId, data.getJSONObject("status").toString(), data.getJSONArray("chars").toString(), data.getJSONArray("skins").toString(), data.getJSONArray("assistChars").toString(), data.getJSONArray("charInfoMap").toString(), DF.format(new Date()));
        }else {
            accountDataServer.updateByKookId(KookId, data.getJSONObject("status").toString(), data.getJSONArray("chars").toString(), data.getJSONArray("skins").toString(), data.getJSONArray("assistChars").toString(), data.getJSONArray("charInfoMap").toString(), DF.format(new Date()));
        }
        return arknightsData;
    }

    private static String Json = "[\n" +
            "  {\n" +
            "    \"type\": \"card\",\n" +
            "    \"theme\": \"success\",\n" +
            "    \"size\": \"lg\",\n" +
            "    \"modules\": [\n" +
            "      {\n" +
            "        \"type\": \"section\",\n" +
            "        \"text\": {\n" +
            "          \"type\": \"kmarkdown\",\n" +
            "          \"content\": \"(met)%s(met)  ***你的明日方舟数据如下:***\"\n" +
            "        }\n" +
            "      },\n" +
            "      {\n" +
            "        \"type\": \"divider\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"type\": \"section\",\n" +
            "        \"text\": {\n" +
            "          \"type\": \"paragraph\",\n" +
            "          \"cols\": 3,\n" +
            "          \"fields\": [\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**游戏名**\\n%s\"\n" +
            "            },\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**等级**\\n%d\"\n" +
            "            },\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**注册时间**\\n%s\"\n" +
            "            }\n" +
            "          ]\n" +
            "        }\n" +
            "      },\n" +
            "      {\n" +
            "        \"type\": \"section\",\n" +
            "        \"text\": {\n" +
            "          \"type\": \"kmarkdown\",\n" +
            "          \"content\": \"***签名：***(font)%s(font)[purple]\"\n" +
            "        }\n" +
            "      },\n" +
            "      {\n" +
            "        \"type\": \"section\",\n" +
            "        \"text\": {\n" +
            "          \"type\": \"paragraph\",\n" +
            "          \"cols\": 2,\n" +
            "          \"fields\": [\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**干员数量**\\n%d\"\n" +
            "            },\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**皮肤数量**\\n%d\"\n" +
            "            },\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**精二干员数量**\\n%d\"\n" +
            "            },\n" +
            "            {\n" +
            "              \"type\": \"kmarkdown\",\n" +
            "              \"content\": \"**三级模组数量**\\n%d\"\n" +
            "            }\n" +
            "          ]\n" +
            "        }\n" +
            "      },\n" +
            "      {\n" +
            "        \"type\": \"divider\"\n" +
            "      }\n" +
            "    ]\n" +
            "  }\n" +
            "]";
}
